//
//  Foundation+TS.swift
//  TSKit
//
//  Created by chenyusen on 2018/3/16.
//

import Foundation

// 以下实现引用自王巍的Swifter一书

public typealias Task = (_ cancel: Bool) -> Void


/// 延迟执行任务
///
/// - Parameters:
///   - time: 延迟执行的时长
///   - task: 待执行的任务
/// - Returns: 可用于提前取消延迟计划
@discardableResult
public func delay(_ time: TimeInterval, task: @escaping ()->()) ->  Task? {
    
    func dispatch_later(block: @escaping ()->()) {
        let t = DispatchTime.now() + time
        DispatchQueue.main.asyncAfter(deadline: t, execute: block)
    }
    
    
    var closure: (()->Void)? = task
    var result: Task?
    
    let delayedClosure: Task = {
        cancel in
        if let internalClosure = closure {
            if (cancel == false) {
                DispatchQueue.main.async(execute: internalClosure)
            }
        }
        closure = nil
        result = nil
    }
    
    result = delayedClosure
    
    dispatch_later {
        if let delayedClosure = result {
            delayedClosure(false)
        }
    }
    
    return result;
}

public func cancel(_ task: Task?) {
    task?(true)
}
